const glob = require('glob')
const { resolve } = require('path')
const mongoose = require('mongoose')
const db = 'mongodb://localhost/hm'
mongoose.Promise = global.Promise


export const initSchemas = () => {
    glob.sync(resolve(__dirname, './schemas/*.js')).forEach(require)
}

export const initAdmin = () => {

}

export const connect = () =>{
    let maxConnectionTimes = 5

    return new Promise((resolve, reject) => {
        mongoose.connect(db)
        const mcn = mongoose.connection

        mcn.on('disconnected', () => {
            maxConnectionTimes--
            if(maxConnectionTimes > 0){
                mongoose.connect(db)
            }else {
                throw new Error('数据库连接次数用完，连接出错')
            }
        })

        mcn.on('error', (err) => {
            reject(err)
        })

        mcn.once('open', () => {
            resolve()
            console.log('Mongodb Connected Successfully!')
        })
    })
}